package com.bonuo.crm.service.impl;

import com.bonuo.crm.domain.Activity;
import com.bonuo.crm.domain.Year;
import com.bonuo.crm.domain.vo.CrmIndex;
import com.bonuo.crm.mapper.*;
import com.bonuo.crm.service.ActivityService;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ActivityServiceImpl implements ActivityService {
    @Autowired
    private ActivityMapper activityMapper;
    @Autowired
    private ProvinceMapper provinceMapper;
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private YearMapper yearMapper;
    @Autowired
    private PlanMapper planMapper;
    @Autowired
    VisitMapper visitMapper;
    @Override
    @DataScope(provinceAlias = {"activity_record"})
    public List<Activity> selectActivityList(Activity activity) {
        return activityMapper.selectActivityList(activity);
    }

    @Override
    public Integer insertActivity(Activity activity) {
        return activityMapper.insertActivity(activity);
    }

    @Override
    public Integer deleteActivityById(Integer id) {
        return activityMapper.deleteActivityById(id);
    }

    @Override
    public Integer updateActivity(Activity activity) {
        return activityMapper.updateActivity(activity);
    }

    @Override
    public Integer selectRepeatActivity(Activity activity) {
        return activityMapper.selectRepeatActivity(activity);
    }

    @Override
    public Map<String, Object> crmIndex(Integer userId) {
        HashMap<String, Object> map = new LinkedHashMap<>();
        String collect = "";
//        //当月的项目收集，销售跟单，销售机会
//        Integer ProjectCollect = activityMapper.getSameMonthCountProcess(1, createBy);
//        Integer salesMerchandiser = activityMapper.getSameMonthCountProcess(2, createBy);
//        Integer saleChance = activityMapper.getSameMonthCountProcess(3, createBy);
//        //当月拜访记录
//        Integer visitNum = activityMapper.getSameMonthCountVisit(createBy);
//        map.put("ProjectCollect", ProjectCollect);
//        map.put("salesMerchandiser", salesMerchandiser);
//        map.put("saleChance", saleChance);
//        map.put("visitNum", visitNum);

        //近一个月的项目收集，销售跟单，销售机会
        //大屏：当月展示柱状图数据
        CrmIndex projectCollectList = activityMapper.getOneMonthCount(1, userId);
        CrmIndex salesMerchandiserList = activityMapper.getOneMonthCount(2, userId);
        CrmIndex saleChanceList = activityMapper.getOneMonthCount(3, userId);
        //近一个月的拜访记录
        CrmIndex visitNumList = activityMapper.getOneMonthCountVisit(userId);
        //近一个月的市场活动
        CrmIndex marketActivityList = activityMapper.getOneMonthCountActivity(userId);
        //近一个月的周报信息
        CrmIndex weeklyReportList = activityMapper.getOneMonthCountWeeklyNewspaper(userId);
        map.put("projectCollectList", projectCollectList);
        map.put("salesMerchandiserList", salesMerchandiserList);
        map.put("saleChanceList", saleChanceList);
        map.put("visitNumList", visitNumList);
        map.put("marketActivityList", marketActivityList);
        map.put("weeklyReportList", weeklyReportList);


        //先查询财年区间
        Year year = yearMapper.selectStartAndEndDate();
        //如果财年不存在，或未分配那么不查询其他数据
        if (year == null) {
            map.put("content", "当前未分配财年");
            return map;
        }


        //查询该用户总业绩
        String province = SecurityUtils.getLoginUser().getUser().getProvince();
        if(StringUtils.isBlank(province)){
            map.put("content", "当前用户未分配省份");
        }else {
            if (province.contains(",")) {
                String[] split = province.split(",");
                // 拼接每个省份的‘’
                collect = Arrays.stream(split)
                        .map(s -> "'" + s.trim() + "'")
                        .collect(Collectors.joining(","));
            } else {
                collect = "'" + province + "'";
            }
            // 大屏：总业绩和财年
            BigDecimal totalSaleAmount = planMapper.selectTotalSaleAmount(collect,year.getYear());
            if (totalSaleAmount == null) {
                totalSaleAmount = BigDecimal.ZERO;
            }
            map.put("text",year.getYear()+"财年业绩目标(万元)");
            map.put("totalSaleAmount", totalSaleAmount);
            //大屏：已完成业绩和完成比例
            // 查询该用户已完成业绩
            //BigDecimal completeAmount = projectMapper.selectAmountByUserId(userId,year.getStartDate(),year.getEndDate());
            BigDecimal completeAmount = projectMapper.selectAmountByProvince(collect,Integer.parseInt(year.getYear()));
            if (completeAmount == null) {
                completeAmount = BigDecimal.ZERO;
            }
            map.put("completeAmount", completeAmount);
            // 完成比例
            if (completeAmount.compareTo(BigDecimal.ZERO) == 0) {
                map.put("completeRatio", BigDecimal.ZERO);
            } else {
                if(totalSaleAmount.equals(BigDecimal.ZERO)){
                    map.put("completeRatio", BigDecimal.ZERO);
                }else {
                    map.put("completeRatio", completeAmount.divide(totalSaleAmount, 2, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)));
                }
            }

//            // 未完成业绩
//            map.put("unAmount", totalSaleAmount.subtract(completeAmount));
//            // 未完成比例
//            if (totalSaleAmount.compareTo(BigDecimal.ZERO) == 0) {
//                map.put("unCompleteRatio", BigDecimal.ZERO);
//            } else {
//                map.put("unCompleteRatio", totalSaleAmount.subtract(completeAmount).divide(totalSaleAmount, 2, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)));
//            }
        }

        //大屏第三块
        //查询本财年项目收集
        Integer projectCollectByYear = projectMapper.selectProjectCollegeOrChange(userId,year.getStartDate(),year.getEndDate(),1);
        //查询本财年项目机会
        Integer saleChanceByYear = projectMapper.selectProjectCollegeOrChange(userId,year.getStartDate(),year.getEndDate(),3);
        //查询本财年市场活动
        Integer marketActivityByYear = activityMapper.marketActivityByYear(userId,year.getStartDate(),year.getEndDate());
        //查询本财年拜访记录
        Integer visitNumByYear = visitMapper.visitNumByYear(userId,year.getStartDate(),year.getEndDate());
        map.put("projectCollectByYear", projectCollectByYear);
        map.put("saleChanceByYear", saleChanceByYear);
        map.put("marketActivityByYear", marketActivityByYear);
        map.put("visitNumByYear", visitNumByYear);

        return map;
    }
}
